<?php

class Soul_Request_Http_Router {

	protected $domain = NULL;
	protected $component = NULL;
	protected $controller = NULL;
	protected $action = NULL;

	public function __construct() {
		$this->initialize();
	}

	protected function initialize(){}

	public function getComponent() {
		return $this->component;
	}

	public function getController() {
		return $this->controller;
	}

	public function getAction() {
		return $this->action;
	}
	
	public function getDomain(){
		return $this->domain;
	}

	public function getBaseUrl() {
		return $this->getDomain()->getBaseUrl();
	}
    
    public function findHistory($startUrl){
    	$startUrl = $this->buildUrl($startUrl);
    	$history = $GLOBALS[RC]->getSession()->get('routehistory', array());
    	krsort($history);
    	foreach($history as $item){
    		if(Soul_Util_String::startsWith($item, $startUrl)){
    			return $item;
    		}
    	}
    	return $startUrl;
    }    

	public function route($url = NULL){
		$pr = $this->parseUrl($url);
		$this->domain = $pr['domain'];
		$this->component = $pr['component'];
		$this->controller = $pr['controller'];
		$this->action = $pr['action'];
		if(isset($pr['args'])){
			$_GET = array_merge($pr['args'], $_GET);
			$_REQUEST = array_merge($_REQUEST, $_GET);
		}
        
		if($GLOBALS[RC]->getRequest()->isGet()){
			$sess = $GLOBALS[RC]->getSession();
			$history = $sess->get('routehistory', array());
			if(count($history) == 10){
				array_shift($history);
			}
			$history[] = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			$sess->set('routehistory', $history);
		}        
	}    

	public function buildUrl($url, $arguments = NULL){
		$urls = explode('/', $url);
		$currentDomain = $urls[0] == '*'? $this->domain: Soul_Config::getDomain($urls[0], TRUE);
		$urls[0] = $currentDomain->getBaseUrl();
		$urls[1] = $urls[1] == '*'? $this->getComponent(): $urls[1];
		$urls[2] = $urls[2] == '*'? $this->getController(): $urls[2];
		$urls[3] = $urls[3] == '*'? $this->getAction(): $urls[3];
		
		if($urls[1] == 'index' && $urls[2] == $urls[1] && $urls[3] == $urls[1]){
			$domainUrl = $urls[0];
		}else{
			$domainUrl = implode('/', $urls);
		}
		if(substr($domainUrl, 0, 2) == '//'){
			$domainUrl = substr($domainUrl, 2);
		}
		
		if(!empty($arguments) && is_array($arguments)){
			Soul_Util_Array::removeEmpty($arguments);
			ksort($arguments);
			$domainUrl .= '/'.str_replace('=', '/', urldecode(http_build_query($arguments, NULL, '/')));
		}

		$result = '';//$this->getBaseUrl();
		if(!Soul_Util_Enviroment::isRewritable()){
			$result .= 'index.php';
		}
		$result .= $domainUrl.'/';
		if(substr($result, -2) == '//'){
			$result = substr($result, 0, -2);
		}		
		return 'http://'.$currentDomain->getHostName().($_SERVER['SERVER_PORT'] == 80? '':':'.$_SERVER['SERVER_PORT']).'/'.$result;
	}

	public function parseUrl($url = NULL) {
		$result = array();
		$url = is_null($url)? $_SERVER['REQUEST_URI']: $url;

		if(!Soul_Util_Enviroment::isRewritable()){
			$url = substr($url, strpos($url, 'index.php') + strlen('index.php'));
		}
		 
		$url = Soul_Util_String::subString($url, '?');
		if(empty($url)){
			$url = '/';
		}

		$host = $_SERVER['SERVER_NAME'];
		foreach(Soul_Config::$domains as $domain){
			$tempUrl = (strlen($url) > 1 && $url[0] == '/')? substr($url, 1): $url;
			if($domain->getHostName() == $host && 
			   substr($tempUrl, 0, strlen($domain->getBaseUrl())) == $domain->getBaseUrl()){
			   	$result['domain'] = $domain;
			   	$url = $tempUrl;
			   	break;
			}
		}
		
		if(!isset($result['domain'])){
			$result['domain'] = Soul_Config::getDomain(NULL, TRUE);
		}
		
		$url = substr($url, strlen($result['domain']->getBaseUrl()));
		if(strlen($url) == 0 || $url == '/'){
			$result['component'] = 'index';
			$result['controller'] = 'index';
			$result['action'] = 'index';
		}else{
			if($url[0] == '/'){
				$url = substr($url, 1);
			}
			if(substr($url, -1) == '/'){
				$url = substr($url, 0, -1);
			}

			$arr = explode('/', $url);
			if(count($arr) < 3){
				if(Soul_Config::$debug){
					print_r($this);
					print_r($_SERVER);
				}
				die('error url');
			}

			$argUrl = array();
			$result['component'] = array_shift($arr);
			$result['controller'] = array_shift($arr);
			$result['action'] = array_shift($arr);
			while(count($arr) > 0){
				$argUrl[] = array_shift($arr).'='.array_shift($arr);
			}
			if(count($argUrl) > 0){
				parse_str(implode('&', $argUrl), $output);
				$result['args'] = $output;
			}
		}
		return $result;
	}
}